package aspectos;

import java.util.*;

import dominio.Persona;
import adicionales.Tupla;
import annotations.Monitored;
							
public aspect ContadorLlamadasAspect{
	
	private int counterSet = 0;
	private int counterGet = 0;
	private Map<Object,Tupla> map = new HashMap<Object,Tupla>();
	
	pointcut fieldMonitoringWrite():
	call(@Monitored * set*(..));
	
	pointcut fieldObtain() :
	call(@Monitored * get*(..));  
	
	before(): fieldMonitoringWrite(){
		Object tmp = thisJoinPoint.getTarget();
		this.copiarContadores(tmp);
		this.counterSet ++;
		this.agregarAlMap(tmp);
	}
	
	before() : fieldObtain(){
		Object tmp = thisJoinPoint.getTarget();
		this.copiarContadores(tmp);
	    this.counterGet ++;
		this.agregarAlMap(tmp);
	}
	
	public int cantLlamadas(Object p1, Object st){
		if(map.containsKey(p1)){
			return this.searchFor(p1,st);
		}else{
			return 0;
		}
		
	}
	
	protected int searchFor(Object p1, Object st) {
		Tupla t = map.get(p1);
		if(st == "getNombre"){
			return t.getVal1();
		}else{
			return t.getVal2();
		}		
	}

	protected void copiarContadores(Object target){
		if(map.containsKey(target)){
			Tupla temp = map.get(target);
			this.counterGet = temp.getVal1();
			this.counterSet = temp.getVal2();
		}else{
			this.counterGet = 0;
			this.counterSet = 0;
		}
	}
	
	private void agregarAlMap(Object target) {
		map.put(target, new Tupla(counterGet, counterSet));
	}

	
}
